from dataclasses import dataclass, asdict
import json
from task import Task
from typing import Dict, Any, List, Optional

class MessageType:
    SUBMIT_TASK = "submit_task"          # 提交任务
    TASK_RESULT = "task_result"          # 任务结果
    FORWARD_TASK = "forward_task"        # 转发任务
    NODE_STATUS = "node_status"          # 节点状态
    GET_STATUS = "get_status"           # 获取节点状态

@dataclass
class NodeInfo:
    """节点信息"""
    node_id: str
    host: str
    port: int
    compute_capacity: float
    current_load: float = 0.0

@dataclass
class TaskResult:
    """任务结果"""
    task_id: str
    success: bool
    result_data: bytes
    submit_time: float
    completion_time: float
    max_delay: float
    execution_path: List[str]  # 记录任务经过的节点

def serialize_task_with_path(task: Task, source_node: str, 
                           execution_path: List[str], client_address: tuple) -> str:
    """序列化任务信息，包含执行路径"""
    task_dict = asdict(task)
    task_dict['task_type'] = task_dict['task_type']
    message = json.dumps({
        'task': task_dict,
        'source_node': source_node,
        'execution_path': execution_path,
        'client_address': client_address
    })
    return message

def deserialize_task_with_path(data: str) -> tuple[Task, str, List[str], tuple]:
    """反序列化任务信息"""
   
    
    print(f"反序列化数据长度: {len(data)}")
    data_dict = json.loads(data)
    task_dict = data_dict['task']
    return (Task(**task_dict), 
            data_dict['source_node'],
            data_dict['execution_path'],
            tuple(data_dict['client_address']))

def serialize_result(result: TaskResult) -> str:
    """序列化任务结果"""
    result_dict = asdict(result)
    result_dict['result_data'] = result_dict['result_data'].hex()
    message = json.dumps(result_dict)
    return message

def deserialize_result(data: str) -> TaskResult:
    """反序列化任务结果"""
   
    result_dict = json.loads(data)
    result_dict['result_data'] = bytes.fromhex(result_dict['result_data'])
    return TaskResult(**result_dict) 